package com.ztjava.weixin.controller;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Page;
import com.ztjava.core.Constant;
import com.ztjava.core.annotation.ControllerClass;
import com.ztjava.core.base.BaseController;
import com.ztjava.core.client.PortalClient;
import com.ztjava.ext.auth.annotation.UserController;
import com.ztjava.ext.auth.annotation.UserMethod;
import com.ztjava.plugin.weixin.WeixinKit;
import com.ztjava.plugin.weixin.WeixinSdk;

@ControllerClass(path="/weixin",client=PortalClient.class)
@UserController(portal=Constant.P_PORTAL)
public class WeixinPortalController extends BaseController {
	/*************
	 *Rule列表
	**************/
	@UserMethod("WeixinMaterial")
	public void materialList(){
		if(!getPara("is_ajax","F").equals("T")){
			keepPara("type");
			render("materialList.html");
			return;
		}
		String type = getPara("type","image");
		WeixinSdk weixinSdk = WeixinKit.use();
		Integer offset = getParaToInt("pageSize",20)*(getParaToInt("pageNumber",1)-1);
		JSONObject result = weixinSdk.material_batchget(type, offset, getParaToInt("pageSize",20));
		List<JSONObject> list = new ArrayList<JSONObject>();
		if(result==null){
			renderPageJson(new Page<JSONObject>(list, 1, 20, 0,0));
		}else {
			JSONArray items = result.getJSONArray("item");
			for(int i=0;i<items.size();i++){
				list.add(items.getJSONObject(i));
			}
			renderPageJson(new Page<JSONObject>(list, getParaToInt("pageNumber",1), getParaToInt("pageSize",20), 0,result.getInteger("total_count")));
		}
	}

	@UserMethod("WeixinMaterial")
	public void batchDeleteMaterial(){
		String[] btSelectItem = getParaValues("btSelectItem");
		WeixinSdk weixinSdk = WeixinKit.use();
		Integer num = 0;
		Integer success = 0;
		for(String media_id:btSelectItem){
			if(weixinSdk.material_del(media_id).getStr(Constant.RESULT).equals(Constant.SUCCESS)){
				success = success + 1;
			}
			num = num + 1;
		}
		renderSuccess("共"+num+"条素材，成功删除"+success+"条");
	}
	@UserMethod("WeixinMaterial")
	public void addMaterial(){
		render("addMaterial.html");
	}
}
